const express = require('express')
const router = express.Router()
const { getDb, saveDb } = require('../db')
// 模拟实现一个中间件
function middleWare(options) {
  return (req, res, next) => {
    console.log('options', options)
    next()
  }
}
router.use(middleWare({ name: '中间件' }))
router.get('/todos', async (req, res) => {
  try {
    const db = await getDb()
    res.status(200).json(db.todos)
  } catch (err) {
    next(err)
  }
})
router.get('/todo/:id', async (req, res) => {
  try {
    const db = await getDb()
    const todo = db.todos.filter(item => String(item._id) === req.params.id)[0]
    res.status(200).json(todo)
  } catch (err) {
    next(err)
  }
})
router.post('/todo', async (req, res) => {
  try {
    const todo = req.body
    if (!todo.title) {
      return res.status(422).json({
        error: 'The field title is required.'
      })
    }
    const db = await getDb()
    const lastTodo = db.todos[db.todos.length - 1]
    todo._id = lastTodo ? lastTodo._id + 1 : 1
    db.todos.push(todo)
    await saveDb(db)
    res.status(200).json(todo)
  } catch (err) {
    next(err)
  }
})
router.patch('/todo', async (req, res) => {
  try {
    const todo = req.body
    if (todo.title == null) {
      res.status(500).json({
        error: 'The field title is required.'
      })
    }
    const db = await getDb()
    const target = db.todos.filter(item => String(item._id) === String(todo._id))[0]
    Object.assign(target, todo)
    await saveDb(db)
    res.status(200).json(target)
  } catch (err) {
    next(err)
  }
})
router.delete('/todo/:id', async (req, res) => {
  try {
    const db = await getDb()
    const result = db.todos.filter(item => String(item._id) !== req.params.id)
    await saveDb({ todos: result })
    res.status(200).json('success')
  } catch (err) {
    next(err)
  }
})
module.exports = router
